import { StorageKey, PermissionType } from '@/constant';
import api from '@/apis/api';
import { PermissionTree2List } from '@/utils/tools';
/*
缓存操作，对localStorage和sessionStorage封装
localStorage:永久存储，浏览器关闭后数据不会丢失
sessionStorage：浏览器关闭后数据自动删除
*/
const appStorage = {
  setLocal(key, value) {
    localStorage.setItem(key, JSON.stringify(value))
  },
  setSession(key, value) {
    sessionStorage.setItem(key, JSON.stringify(value))
  },
  getLocal(key) {
    let value = localStorage.getItem(key)
    if (value !== undefined && value !== 'undefined') {
      return JSON.parse(value)
    } else {
      return null
    }
  },
  getSession(key) {
    let value = sessionStorage.getItem(key)
    if (value !== undefined && value !== 'undefined') {
      return JSON.parse(value)
    } else {
      return null
    }
  },
  removeLocal(key) {
    localStorage.removeItem(key)
  },
  removeSession(key) {
    sessionStorage.removeItem(key)
  },
  clearLocal() {
    localStorage.clear()
  },
  clearSession() {
    sessionStorage.clear()
  },
  clearAll() {
    localStorage.clear()
    sessionStorage.clear()
  },
  //登陆成功后初始化
  initData(token, userInfo, remberme, next) {
    //存储缓存
    this.setSession(StorageKey.TOKEN, token)
    this.setSession(StorageKey.USER, userInfo)
    if (remberme) {
      this.setLocal(StorageKey.USER)
    }
    else {
      this.removeLocal(StorageKey.USER)
    }
    //获取用户菜单权限并动态注册路由
    let p1 = new Promise((resolve, reject) => {
      api.permission.myTree(PermissionType.MENU, resp => {
        this.setSession(StorageKey.PERMISSION_MENU, resp.data)
        // console.log('存储菜单')
        resolve()
      })
    })
    //获取用户操作权限并缓存
    let p2 = new Promise((resolve, reject) => {
      api.permission.myTree(PermissionType.OPERATOR, resp => {
        //将树形结构转成list方便查找
        let list = PermissionTree2List(resp.data)
        this.setSession(StorageKey.PERMISSION_OPERATOR, list)
        // console.log('存储权限')
        resolve()
      })
    })
    //初始化数据字典
    let p3 = new Promise((resolve, reject) => {
      api.dict.getTree(null, resp => {
        let dicts = {}
        for (let item of resp.data) {
          let tmp = {
            code: item.code,
            name: item.name,
            children: []
          }
          for (let child of item.children) {
            let childTmp={
              code: child.code,
              name: child.name,
            }
            // tmp.children[child.code] = childTmp
            tmp.children.push(childTmp)
          }
          dicts[item.code] = tmp
        }
        this.setSession(StorageKey.DICT, dicts)
        // console.log('存储数据字典')
        resolve()
      })
    })
    Promise.all([p1, p2, p3]).then(() => {
      // console.log('开始跳转')
      next()
    });
  },
}
export default appStorage
